#!/usr/bin/env python

import sys, os
import jabber.jabber as jabber
import ConfigParser
from colorize_text import colorize

cfg = ConfigParser.ConfigParser()
#cfg.read(os.path.join(os.environ["HOME"], ".jabber_bot.ini"))
cfg.read("/etc/yoshiiibox.ini")

server	 = cfg.get("jabber", "server")
user	 = cfg.get("jabber", "user")
password = cfg.get("jabber", "password")
resource = cfg.get("jabber", "resource")
receiver = cfg.get("jabber", "receiver")

def message_callback(con, msg):
# inspect the jabber.Message() object
    print "Body", msg.getBody()
    print "From", msg.getFrom()
    print "Name", msg.getName()
    print "Type", msg.getType()

def message_dispatcher(con, msg):
    rxBody = msg.getBody()
    txBody = ""
    if type(rxBody) != type(u""): 
	print colorize(repr(rxBody), "blue")
	return
    print colorize(repr(rxBody), "red")

    if rxBody.startswith("ip"):
	txBody += "ip=%s port=%i"%con._sock.getsockname()
    elif rxBody.startswith("users"):
	txBody += os.popen("w").read()
#    elif rxBody.startswith("pstree"):
#	txBody += os.popen("pstree").read()
#    elif "help" in rxBody.split() or "usage" in rxBody.split():
#	txBody += usage()
    else:
	txBody = msg.getBody()
#    con.send(jabber.Message(msg.getFrom(), txBody))
    # send everything to the registered receiver...
    con.send(jabber.Message(receiver, txBody))
    print colorize(receiver, 'blue')
    print colorize(txBody, 'green')

#client = jabber.Client(server, debug=jabber.DBG_ALWAYS, log=sys.stderr)
client = jabber.Client(server, log=sys.stderr)
client.registerHandler("message", message_dispatcher)
client.setDisconnectHandler(lambda x:x)
client.connect()
import atexit
atexit.register(client.disconnect)
assert client.auth(user, password, resource) != 0, "authentication failed" 
client.sendInitPresence()

#roster = client.requestRoster()
#print "online:", roster.getJIDs()

try:
    while True:
	client.process(10)
except KeyboardInterrupt:
    pass
